<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>"私有"模式实现Counter</TITLE>
</HEAD>

<BODY>

<script>
	if (!Function.prototype.bind) {
		Function.prototype.bind = function(context) {
			var args = Array.prototype.slice.call(arguments, 1);
			var that = this;
			return function() {
				return that.apply(context, args.concat(Array.prototype.slice
						.call(arguments)));
			}
		}
	}
	(function() {
		//定义方法
		var methods = {
			add : function(data) {
				data.i++;
				return this;
			},
			sub : function(data) {
				data.i--;
				return this;
			},
			get : function(data) {
				return data.i;
			}
		};
		function createCounter(num) {

			//定义返回对象
			var ret = {};

			//定义私有数据
			var data = {
				i : num||0
			};

			//关联数据与方法，构成一个模块
			for ( var methodName in methods) {
				ret[methodName] = methods[methodName].bind(ret, data);
			}
			//返回对象
			return ret;
		}
		window.createCounter = createCounter;
	})();

	var Counter = createCounter(1);
	alert(Counter.add().add().sub().get());//2
</script>
</BODY>
</HTML>